import Vue from 'vue'
import Router from 'vue-router'
import Index from "../components/Index";
import AboutMe from "../components/about/AboutMe";
import QuestionList from "../components/question/QuestionList";
import Article from "../components/article/Article";
import Login from "../components/Login";
import Main from "../components/Main";
import ShowArticle from "../components/article/ShowArticle";
import ShowQuestion from "../components/question/ShowQuestion";
import Manage from "../components/manage/Manage";
import { Message } from 'element-ui'
// Vue.use(Message)
Vue.prototype.$message = Message

Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      redirect:'/login'
    },
    {
      path: '/main',
      component: Main,
      children:[
        {
          path: '/index',
          name:"index",
          component: Index
        },
        {
          path: '/about',
          name:"about",
          component: AboutMe
        },
        {
          path: '/question',
          name:"question",
          component: QuestionList
        },
        {
          path: '/article',
          name:"article",
          component: Article
        },
        {
          path: '/showArticle',
          name:"showArticle",
          component: ShowArticle
        },
        {
          path: '/showQuestion',
          name: 'showQuestion',
          component: ShowQuestion
        },
        {
          path: '/manage',
          name: 'manage',
          component: Manage
        },
      ]
    },
    {
      path: '/login',
      component: Login,
      name:'login'
    }
  ]


})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  console.log('navigation-guards');
  // console.log(sessionStorage.getItem("user"));
// to: Route: 即将要进入的目标 路由对象
// from: Route: 当前导航正要离开的路由
// next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。

  const nextRoute = ['main','index', 'about', 'question', 'article', 'showArticle','showQuestion','manage'];
// 未登录状态；当路由到nextRoute指定页时，跳转至login
  if (nextRoute.indexOf(to.name) >= 0) {
    if (sessionStorage.getItem("user")==null) {
      Vue.prototype.$message({
        message:"您未登录，已为您跳转到登录页面",
        type:"error"
      })
      router.push({ name: 'login' })
    }
  }
// 已登录状态；当路由到login时，跳转至home
  if (to.name === 'login') {
    if (sessionStorage.getItem("user")!=null) {
      router.push({ name: 'index' });
    }
  }
  next();
});

export default router;


